package com.frogs.ucenter.v1.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.httpclient.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.frogs.framework.util.PageList;
import com.frogs.framework.util.PageTurn;
import com.frogs.framework.util.StringUtil;
import com.frogs.system.util.UserMessageStatusEnum;
import com.frogs.system.util.UserMessageTypeEnum;
import com.frogs.system.web.api.request.Request;
import com.frogs.system.web.api.response.Response;
import com.frogs.system.web.api.response.Response.ApiResultEnum;
import com.frogs.system.web.exception.ServiceOperationException;
import com.frogs.ucenter.dao.UserMessageDmContentDao;
import com.frogs.ucenter.dao.UserMessageDmDao;
import com.frogs.ucenter.dao.UserMessageDmOperRecordDao;
import com.frogs.ucenter.dao.UserMessageDmReceiverDao;
import com.frogs.ucenter.entity.UserMessageDm;
import com.frogs.ucenter.entity.UserMessageDmContent;
import com.frogs.ucenter.entity.UserMessageDmOperRecord;
import com.frogs.ucenter.entity.UserMessageDmReceiver;
import com.frogs.ucenter.entity.UserMessageDmWithContent;
import com.frogs.ucenter.v1.request.DirectMessageBatchUpdateRequest;
import com.frogs.ucenter.v1.request.DirectMessageCountRequest;
import com.frogs.ucenter.v1.request.DirectMessageListRequest;
import com.frogs.ucenter.v1.request.DirectMessageReadRequest;
import com.frogs.ucenter.v1.request.DirectMessageSendRequest;
import com.frogs.ucenter.v1.response.DefaultResponse;
import com.frogs.ucenter.v1.response.PageListResponse;
import com.frogs.ucenter.v1.response.ShowResponse;
import com.frogs.ucenter.v1.service.DirectMessageService;
import com.frogs.ucenter.v1.util.ApiConstants;

@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class) 
@Service(ApiConstants.VERSION+"directMessageService")
public class DirectMessageServiceImpl implements DirectMessageService{

	private final static Logger log = LoggerFactory.getLogger(DirectMessageServiceImpl.class);
	
	@Resource
	private UserMessageDmDao userMessageDmDao;
	
	@Resource
	private UserMessageDmReceiverDao userMessageDmReceiverDao;
	
	@Resource
	private UserMessageDmContentDao userMessageDmContentDao;
	
	@Resource
	private UserMessageDmOperRecordDao userMessageDmOperRecordDao; 
	
	@Override
	public Response send(Request request) throws Exception {
		Response response = new DefaultResponse();
		DirectMessageSendRequest directMessageSendRequest = (DirectMessageSendRequest) request;
		try {
			//插入内容
			UserMessageDmContent userMessageDmContent = new UserMessageDmContent();
			userMessageDmContent.setContent(directMessageSendRequest.getContent());
			userMessageDmContent.setSubject(directMessageSendRequest.getSubject());
			userMessageDmContent.setContentType(UserMessageTypeEnum.CONTENT_CUSTOM.getId());
			userMessageDmContentDao.insert(userMessageDmContent);
			
			int contentId = userMessageDmContent.getId();
			
			UserMessageDm userMessageDm = new UserMessageDm();
			
			userMessageDm.setSender(directMessageSendRequest.getSender());
			userMessageDm.setSenderId(directMessageSendRequest.getSenderId());
			userMessageDm.setContentId(contentId);
			userMessageDm.setApplicableId(directMessageSendRequest.getApplicableId());
			userMessageDm.setSendType(directMessageSendRequest.getSendType());
			userMessageDm.setReceiverType(directMessageSendRequest.getReceiverType());
			
			if(!StringUtil.isEmpty(directMessageSendRequest.getOverTime())) {
				userMessageDm.setOverTime(DateUtil.parseDate(directMessageSendRequest.getOverTime()));
			} else {
				userMessageDm.setOverTime(null);
			}
			
			if(!StringUtil.isEmpty(directMessageSendRequest.getSendTime())) {
				userMessageDm.setSendTime(DateUtil.parseDate(directMessageSendRequest.getSendTime()));
			} else {
				userMessageDm.setSendTime(new Date());
			}
			
			userMessageDm.setCreateTime(new Date());
			userMessageDmDao.insert(userMessageDm);
			
			JSONArray receiverArray = directMessageSendRequest.getReceiverArray();
			List<UserMessageDmReceiver> userMessageDmReceiverList =new ArrayList<UserMessageDmReceiver>();
			if(null != receiverArray) {
				for(int i=0; i<receiverArray.size(); i++) {
					JSONObject receiver = receiverArray.getJSONObject(i);
					UserMessageDmReceiver userMessageDmReceiver = new UserMessageDmReceiver();
					
					userMessageDmReceiver.setReceiver(receiver.getString("receiver"));
					userMessageDmReceiver.setUserId(receiver.getString("receiverId"));
					userMessageDmReceiver.setDmId(userMessageDm.getId());
					
					userMessageDmReceiverList.add(userMessageDmReceiver);
					
					if(i!=0 && i%1000==0){
						userMessageDmReceiverDao.batchInsert(userMessageDmReceiverList);
						userMessageDmReceiverList = new ArrayList<UserMessageDmReceiver>();
					}
				}
				if(userMessageDmReceiverList.size() > 0) {
					userMessageDmReceiverDao.batchInsert(userMessageDmReceiverList);
				}
			}
			response.setTip("站内短信发送成功!");
			return response;
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
	}

	/* (non-Javadoc)
	 * 根据用户和短信状态查询短信数量
	 */
	@Override
	public Response countByStatus(Request request) throws Exception  {
		try{
			DirectMessageCountRequest directMessageCountRequest = (DirectMessageCountRequest) request;
			String receiver = directMessageCountRequest.getReceiverId();
			int status = directMessageCountRequest.getStatus();
			String level = directMessageCountRequest.getLevel();
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("eqReceiverId", receiver);
			params.put("eqStatus", status);
			params.put("eqLevel", level);
			ShowResponse<Integer> response = new ShowResponse<Integer>();
			int count = userMessageDmDao.selectCountByMapWithContent(params);
			response.setInfo(count);
			return response;
		}catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
	}

	/**
	 * 获取用户站内信列表
	 * @param request
	 * @return
	 */
	@Override
	public Response getUserMessageDmList(Request request) throws Exception  {
		PageListResponse<UserMessageDmWithContent> response = new PageListResponse<UserMessageDmWithContent>();
		try {
			DirectMessageListRequest listRequest = (DirectMessageListRequest) request;
			Map<String, Object> params = new HashMap<String, Object>();
			
			if(listRequest.getStatus() >= 0) {
				params.put("eqStatus", listRequest.getStatus());
			}
			if(!StringUtil.isEmpty(listRequest.getLevel())) {
				params.put("eqLevel", listRequest.getLevel());
			}
			if(!StringUtil.isEmpty(listRequest.getReceiverId())) {
				params.put("eqReceiverId", listRequest.getReceiverId());
			}
			
			params.put("gtOverTime", new Date());
			
			PageList<UserMessageDmWithContent> list = userMessageDmDao.selectByMapWithContent(params, listRequest.getPageNo(), listRequest.getPageSize());
			if (list != null && list.size() > 0) {
				PageTurn pageTurn = list.getPageTurn();
				response.setPageTurn(pageTurn);
				response.setCode(ApiResultEnum.SUCCESS.getId());
				response.setList(list);
			}
			
			return response;
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
	}

	@Override
	public Response readUserMessageDm(Request request) throws Exception {
		DirectMessageReadRequest readRequest = (DirectMessageReadRequest)request;
		ShowResponse<UserMessageDmWithContent> response = new ShowResponse<UserMessageDmWithContent>();
		try {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("inIdList", readRequest.getIds().split(","));
			params.put("eqReceiverId", readRequest.getReceiverId());
			params.put("eqLevel", readRequest.getLevel());
			PageList<UserMessageDmWithContent> list = userMessageDmDao.selectByMapWithContent(params, 0, 9999);
			
			if(null == list || list.size() == 0) {
				throw new ServiceOperationException("该消息不存在或已删除");
			}
			UserMessageDmWithContent message = list.get(0);
			if(message.getStatus() == UserMessageStatusEnum.DELETE.getId()) {
				throw new ServiceOperationException("该消息已失效");
			}
			//保存读取记录
			mergeUserMessageRecord(readRequest, UserMessageStatusEnum.READ.getId());
			
			response.setInfo(list.get(0));
			return response;
			
		}catch(Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
	}
	
	/**
	 * 修改读取记录状态,每条记录每个用户只能有一个读取状态、或已读、或删除
	 * @param readRequest
	 * @param status
	 */
	private void mergeUserMessageRecord(DirectMessageReadRequest readRequest, int status) {
		Map<String, Object> params = new HashMap<String, Object>();
		for(String id : readRequest.getIds().split(",")) {
			params.put("eqMessageId", id);
			params.put("eqUserId", readRequest.getReceiverId());
			params.put("eqLevel", readRequest.getLevel());
			if(userMessageDmOperRecordDao.selectCountByMap(params) > 0) {
				params.put("status", status);
				userMessageDmOperRecordDao.updateByMap(params);
			} else {
				UserMessageDmOperRecord record = new UserMessageDmOperRecord();
				record.setMessageId(Integer.parseInt(id));
				record.setOperIp(readRequest.getIp());
				record.setOperTime(new Date());
				record.setUserId(readRequest.getReceiverId());
				record.setStatus(status);
				userMessageDmOperRecordDao.insert(record);
			}
		}
	}

	@Override
	public Response batchUpdateUserMessageDm(Request request) throws Exception {
		DirectMessageBatchUpdateRequest updateRequest = (DirectMessageBatchUpdateRequest) request;
		Response response = new DefaultResponse();
		try {
			DirectMessageReadRequest readRequest = new DirectMessageReadRequest();
			readRequest.setApplicableId(updateRequest.getApplicableId());
			readRequest.setIds(updateRequest.getIds());
			readRequest.setIp(updateRequest.getIp());
			readRequest.setReceiverId(updateRequest.getReceiverId());
			mergeUserMessageRecord(readRequest, updateRequest.getStatus());
			response.setTip("更新成功");
			return response;
		} catch(Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
	}
}
